//
//  homeTableVC.swift
//  我的微博
//
//  Created by shmily on 15/7/28.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit

class homeTableVC: BaseTableVC {
    /// 可重用 ID
    let NormalCellID = "NormalCellID"
    let retweetedCellID = "retweetedCellID"
    
    /// 微博内容数据
    var blogArray: [BlogContent]? {
        didSet{
            tableView.reloadData()
        }
    }
    var reuserID: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserInfo.isLogon {
             visitorView?.setUpInfo(true, imgIcon: "visitordiscover_feed_image_house", title: "关注一些人，回这里看看有什么惊喜")
        }
        prepareUI()
        loadData()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "acceptNotification:", name: kNotificationDidSelectItem, object: nil)
    }
    //MARK:- 通知
    var isPresent =  true // 判断是 modal 还是 dismiss...
    /// 获取通知
    func acceptNotification(ns: NSNotification) {
        let urls = ns.userInfo![kNotificationDidSelectUrls]! as! [NSURL]
        let index = ns.userInfo![kNotificationDidSelectIndex] as! Int
        let picVC = PictureBroswerVC(urls: urls, index: index)
        
        //自定义转场动画
        picVC.transitioningDelegate = self
        picVC.modalPresentationStyle = UIModalPresentationStyle.Custom // 自定义
        
        presentViewController(picVC, animated: true, completion: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //加载 UI 内容
    private func prepareUI() {
        refreshControl = RefreshCtrl()
        //刷新时执行该方法  (下拉加载数据)
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        //设置行高
        tableView.estimatedRowHeight = 300
        tableView.registerClass(NormalCell.self, forCellReuseIdentifier: NormalCellID)
        tableView.registerClass(retweetedCell.self, forCellReuseIdentifier: retweetedCellID)
        navigationController?.navigationBar.insertSubview(lblTip, atIndex: 0)
    }
    
    //MARK:- 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return blogArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = blogArray![indexPath.item]
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID.cellID(status), forIndexPath: indexPath) as? HomeTableViewCell
        
        cell?.status = status
        return cell!
    }
    
    //设置行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = blogArray![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID.cellID(status)) as? HomeTableViewCell
    
        //上拉加载数据
        if indexPath.row == blogArray!.count - 1 {
            isPullUp = true
            loadData()
        }
        /// 存在缓存的话,直接调用
        if let rowHeight = status.rowHeight {
            return rowHeight
        }
        //记录下行高
        status.rowHeight = cell!.calRowHeight(status)
        return status.rowHeight!
    }
    
    //MARK:- 加载网络数据
    /// 是否是上拉状态,方便函数调用
    private var isPullUp = false
    /// 加载网络数据
    func loadData() {
        /// 仅仅是加载刷新的动画而已
        refreshControl?.beginRefreshing()
        var sinceId = blogArray?.first?.id ?? 0 //设置 sinceID
        var maxId: Int = 0
        
        if isPullUp {
            sinceId = 0
            maxId = blogArray?.last?.id ?? 0   // 减1是因为防止刷新到相同的微博(max_id 是<=)
        }
         NetworkingTools.sharedNetTool.loadStatus(sinceId,max_id: maxId - 1) { (result, error) -> () in
            if error != nil {
                print(error)
                return
            }
            self.refreshControl?.endRefreshing()
            if result == nil {
                print("刷新失败")
                return
            }
            
            //加载数据
            if sinceId > 0 {  // 下拉
                self.blogArray! = result! + self.blogArray!
                //显示提示消息
                let count = result?.count ?? 0
                self.displayTips(count)

            } else if maxId > 0{  // 上拉
                self.blogArray! += result!
            } else {
                self.blogArray = result
            }
        }
    }
    /// 显示提示框
    private func displayTips(dataCount: Int) {
        refreshControl?.enabled = false
        lblTip.text = (dataCount == 0) ? "暂未有新的动态" : "共加载\(dataCount)条微博"
        let rect = lblTip.frame
        UIView.animateWithDuration(1.5, animations: { () -> Void in
            UIView.setAnimationRepeatAutoreverses(true)
            self.lblTip.frame = CGRectOffset(self.lblTip.frame, 0, 3 * rect.height)
            }) { (_) -> Void in
                self.lblTip.frame = rect
                self.refreshControl?.enabled = true
        }
    }
    
    private lazy var lblTip: UILabel = {
        let rect = CGRect(x: 0, y:-2 * 40, width: UIScreen.mainScreen().bounds.width, height: 40)
        let view = UILabel(frame: rect)
        view.font = UIFont.systemFontOfSize(15)
        view.backgroundColor = UIColor.orangeColor()
        view.textAlignment = NSTextAlignment.Center

        return view
    }()
}

//MARK:- 转场动画代理
extension homeTableVC: UIViewControllerTransitioningDelegate {
   //展示转场的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
    //解除转场的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
}
//设计转场
extension homeTableVC: UIViewControllerAnimatedTransitioning {
    // 动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2.0
    }
    
    // 转场动画的实现
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresent {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // 获取转场结束视图
            transitionContext.containerView()?.addSubview(toView) // 添加到容器中
            toView.alpha = 0
            
            //开始自定义动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                toView.alpha = 1
                }) { (_) -> Void in
                    self.isPresent = false // modal 和 dismiss 交替实现
                    transitionContext.completeTransition(true) // 结束转场
            }
        } else {
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! // 获取转场结束视图
            transitionContext.containerView()?.addSubview(fromView) // 添加到容器中
            fromView.alpha = 1
            
            //开始自定义动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                fromView.alpha = 0
                }) { (_) -> Void in
                    self.isPresent = true
                    transitionContext.completeTransition(true) // 结束转场
            }
        }
    }
    
}



